package io.cloud.tec.project.web;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.util.Base64;

/**
 *
 * Firefox浏览器，访问/favicon.ico时，控制台打印以下日志
 *
 * Content Security Policy: 页面设置阻止读取位于 http://localhost:8081/favicon.ico 的一项资源("default-src")。
 *
 * 网络中的请求的请求头：Referrer 策略strict-origin-when-cross-origin
 *
 * 原因：单独访问某个接口，返回json时，firefox启用built-in的JSON查看器解析展示json。此时会block favicon.ico的请求
 *
 * 具体查看：https://www.5axxw.com/questions/content/9xbdg0
 */
@Controller
public class FaviconController {

    private final String faviconPath = "static/favicon.ico";

    /**
     * consumes的作用是指定处理请求的提交内容类型（Content-Type）,例如application/json, text/html
     * produces的作用是指定返回值类型和返回值编码
     *
     * @return
     * @throws IOException
     */
    @GetMapping(value = "/favicon.ico", produces = "image/x-icon")
    @ResponseBody
    public byte[] favicon1() throws IOException {
        return IOUtils.toByteArray(new ClassPathResource(faviconPath).getInputStream());
    }

    @GetMapping(value = "/favicon.ico")
    public void favicon2() throws IOException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        /**
         * requestAttributes.getResponse().setContentType("image/x-icon");
         */
        IOUtils.copy(new ClassPathResource(faviconPath).getInputStream(), requestAttributes.getResponse().getOutputStream());
    }

    /**
     * 未验证通过，需要前端ajax请求后，处理返回的数据，并赋值给img的src属性
     *
     * @return
     * @throws IOException
     */
    @GetMapping(value = "/favicon.ico"/*, produces = "image/x-icon"*/, produces = "image/x-png;base64")
    @ResponseBody
    public String favicon3() throws IOException {
        String result = "data:image/x-icon;base64," + new String(Base64.getEncoder().encode(IOUtils.toByteArray(new ClassPathResource(faviconPath).getInputStream())));
        // 前端注意替换空格和换行
        result = result.replaceAll(" ", "").replaceAll("\r\n", "");
        return result;
    }
}
